package dk.sdu.mmmi.opn.assignment3easy.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import dk.sdu.mmmi.opn.assignment3easy.acquaintance.ICatalogue;
import dk.sdu.mmmi.opn.assignment3easy.acquaintance.IEntry;
import dk.sdu.mmmi.opn.assignment3easy.acquaintance.Product;

/**
 * Implementation of a product entry, with a mutable quantity
 * (part of the model layer of the application)
 * @author ups
 */
public class EntryImpl extends UnicastRemoteObject implements IEntry {

	/**
	 * The catalogue to which this entry belongs
	 */
	private ICatalogue parent;
		
	/**
	 * The product which this entry concerns
	 */
	private Product product;
	
	/**
	 * The number of products
	 */
	private int quantity;

	/**
	 * Create entry for the given product and with the given quantity
	 */
	public EntryImpl(ICatalogue parent, Product product, int quantity) throws RemoteException {
		this.parent = parent;
		this.product = product;
		this.quantity = quantity;
	}

	/**
	 * Get the quantity
	 */
	@Override
	public int getQuantity() {
		Server.log(false, "EntryImpl::getQuantity");
		return quantity;
	}

	/**
	 * Change the quantity (positive number implies increase, negative number implies reduction)
	 * @throws RemoteException 
	 */
	@Override
	public boolean updateQuantity(int change) throws RemoteException {
		Server.log(false, "EntryImpl::updateQuantity");
		if(change+quantity<0) return false;
		quantity += change;
		parent.notifyObservers(this);
		return true;
	}

	/**
	 * Get the product
	 */
	@Override
	public Product getProduct() {
		Server.log(false, "EntryImpl::getProduct");
		return this.local_getProduct();
	}

	/**
	 * Method added for latency simulation: does not incur latency, so should only be called locally
	 * @return
	 */
	protected Product local_getProduct() {
		return product;
	}

	private static final long serialVersionUID = -6898643554346573120L;
}
